package cn.workreport.util;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.workreport.modules.upload.entity.Upload;
import cn.workreport.modules.upload.enums.BusinessKeyEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.rmi.ServerException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class Base64Util {
    private static final String separator = "/";
//    private final static ExecutorService executor = Executors.newCachedThreadPool();//启用多线程

    // 获取base64字符串
    public static String encodeBase64(String filaName, boolean isSafe) {
        if (StringUtils.isBlank(filaName)) {
            return null;
        }
        InputStream in = null;
        byte[] data = null;
        String encodedText = null;
        //读取图片字节数组
        try {
            in = new BufferedInputStream(new FileInputStream(filaName));
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        if (isSafe) {
            java.util.Base64.Encoder encoder = java.util.Base64.getUrlEncoder();
            encodedText = encoder.encodeToString(data);
        } else {
            Base64Encoder.encode(data);
            encodedText = encodedText.replaceAll("[\\s*\t\n\r]", "");
        }
        return encodedText;
    }

    /**
     * 解析base64成文件
     * @param base64Str base64 字符串
     * @param realPath 文件的存储路径
     * @param fileDir 文件夹-相对路径
     * @param suffix 文件的后缀 如: ".png"
     * @param isSafe
     * @return
     */
    public static String decodeBase64(
            String base64Str,
            String realPath,
            String fileDir,
            String suffix,
            boolean isSafe
    ) {
        if (
                StringUtils.isBlank(base64Str)
                        || StringUtils.isBlank(realPath)
                        || StringUtils.isBlank(fileDir)
                        || StringUtils.isBlank(suffix)
        ) {
            return null;
        }
//        OutputStream out = null;
        // 保存的文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        // 保存文件的相对路径
        String filePath = null;
        // 保存文件的绝对路径
        String fileLocation = null;
        try {
            byte[] b = new byte[2048];
            if (isSafe) {
                java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
                b = decoder.decode(base64Str);
            } else {
                b = Base64Decoder.decode(base64Str.substring(base64Str.indexOf(",") + 1));
            }
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            File dir = new File(realPath + separator + fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            fileLocation = dir + separator + fileName;
            InputStream inputStream = new ByteArrayInputStream(b);
            Img.from(inputStream).setQuality(0.2)//压缩比率
                            .write(FileUtil.file(fileLocation));

//            out = new BufferedOutputStream(new FileOutputStream(fileLocation));
//            out.write(b);
//            out.flush();
            filePath = fileDir + separator + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            if (out != null) {
//                try {
//                    out.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//            }
        }
        log.info("fileLocation ==>" + fileLocation);
        log.info("filePath ==>" + filePath);
        return filePath;
    }
}